package com.mall.product.web;

import com.mall.product.entity.CategoryEntity;
import com.mall.product.service.CategoryService;
import com.mall.product.vo.Catalog2VO;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redissonClient;
    @GetMapping({"/","/index.html","/home","home.html"})
    public String index(Model model){
        List<CategoryEntity> list = categoryService.getLevelCategory();
        model.addAttribute("categorys",list);
        return "index";
    }
    @ResponseBody
    @RequestMapping("/index/catalog.json")
    public Map<String, List<Catalog2VO>> getCatLog2JSON(){
        Map<String, List<Catalog2VO>> map = categoryService.getCatalog2JSON();
        return map;
    }
    @GetMapping("/hello")
    @ResponseBody
    public String hello(){
        final String key = "myLock";
        RLock lock = redissonClient.getLock(key);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            System.out.println("业务处理");
            Thread.sleep(100000);
        } catch (Exception e) {
            e.printStackTrace();
        }finally
        {
            lock.unlock();
            System.out.println("释放锁成功" + Thread.currentThread().getName());
        }
        return "hello";
    }
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor(){
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);
        try {
            door.await();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "关门熄灯...";
    }
    @GetMapping("/goHome/{id}")
    @ResponseBody
    public String goHome(@PathVariable Long id){
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown(); // 递减的操作
        return id + "下班走人";
    }
}
